package com.dissertation.compoent;

import com.alibaba.fastjson.JSON;
import com.dissertation.pojo.Message;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * Created by jsh3 on 17-11-23.
 * 用于检查请求参数是否有问题
 */
@Aspect
@Component
public class ParamChecker {


    @Around( "@annotation(com.dissertation.annotation.CheckBindingResult)" )
    public Object checkBind( ProceedingJoinPoint pjp ) throws Throwable {
        System.out.println("执行");
        Object[] args = pjp.getArgs();
        BindingResult result = null;
        for ( Object arg : args ) {
            if ( arg instanceof BindingResult ) {
                result = (BindingResult) arg;
            }
        }
        if ( result != null && result.hasErrors() ) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            return Message.createErr( JSON.toJSONString( fieldErrors.stream()
                    .map( DefaultMessageSourceResolvable::getDefaultMessage )
                    .collect( toList() ) ) );

        }
        return pjp.proceed( args );
    }
}
